package main

import (
	"bytes"
	"context"
	"math/rand"
	"os"
	"os/signal"
	"path/filepath"
	"telegram-bot-c9121/internal/config"
	"telegram-bot-c9121/internal/logger"

	"github.com/go-telegram/bot"
	"github.com/go-telegram/bot/models"
)

func main() {
	logger.Info("Starting...")

	ctx := context.Background()

	config, err := config.New()
	if err != nil {
		logger.Fatal("Failed to load config", err)
	}

	logger.Debug("Config loaded")

	ctx, cancel := signal.NotifyContext(ctx, os.Interrupt)
	defer cancel()

	opts := []bot.Option{
		bot.WithDebug(),
	}

	b, err := bot.New(config.BotToken(), opts...)
	if err != nil {
		logger.Fatal("Failed to create bot", err)
	}

	b.SetMyCommands(ctx, &bot.SetMyCommandsParams{
		Commands: []models.BotCommand{
			{
				Command:     "/random_image",
				Description: "Send random image",
			},
		},
		Scope:        &models.BotCommandScopeDefault{},
		LanguageCode: "ru",
	})

	b.SetMyDescription(ctx, &bot.SetMyDescriptionParams{
		Description:  "Random image sender",
		LanguageCode: "ru",
	})

	b.RegisterHandler(bot.HandlerTypeMessageText, "/random_image", bot.MatchTypeExact, sendRandomImage)

	b.Start(ctx)
	logger.Info("Bot started")
}

func sendRandomImage(ctx context.Context, b *bot.Bot, update *models.Update) {
	files, err := filepath.Glob("data/images/*.jpeg")
	if err != nil {
		logger.Error("Failed to read dir data/images", err)
	}

	if len(files) == 0 {
		logger.Error("No images found in data/images")
	}

	randFileIndex := rand.Intn(len(files))
	randFilePath := files[randFileIndex]
	randFileData, err := os.ReadFile(randFilePath)
	if err != nil {
		logger.Error("Failed to read image file", err)
	}

	b.SendPhoto(ctx, &bot.SendPhotoParams{
		ChatID: update.Message.Chat.ID,
		Photo: &models.InputFileUpload{
			Filename: files[randFileIndex],
			Data:     bytes.NewReader(randFileData),
		},
	})
}
